package com.kstech.ks_gaz01.fragments

import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankii.androidlibrary.base.BaseBindingFragment
import com.blankii.androidlibrary.utils.CalcUtil
import com.blankii.androidlibrary.utils.HardwareInfoUtil
import com.blankii.androidlibrary.views.DividerItemDecoration
import com.chad.library.adapter4.layoutmanager.QuickGridLayoutManager
import com.google.android.material.tabs.TabLayout
import com.kstech.ks_gaz01.R
import com.kstech.ks_gaz01.SOCKET_PORT
import com.kstech.ks_gaz01.XML_ADDRESS_SAVE_PARAM
import com.kstech.ks_gaz01.XML_CONFIG
import com.kstech.ks_gaz01.XML_REALTIME_FLOAT
import com.kstech.ks_gaz01.XML_XS_RTB
import com.kstech.ks_gaz01.base.FragmentPage
import com.kstech.ks_gaz01.base.HomeViewModel
import com.kstech.ks_gaz01.data.DebugDataBean
import com.kstech.ks_gaz01.data.DebugDataBean.floatDataType
import com.kstech.ks_gaz01.data.DebugDataBean.xmlMap
import com.kstech.ks_gaz01.data.DebugDataItemAdapter
import com.kstech.ks_gaz01.data.DebugDataTitleAdapter
import com.kstech.ks_gaz01.data.GridSpaceItemDecoration
import com.kstech.ks_gaz01.databinding.FragmentConfigBinding
import com.kstech.ks_gaz01.databinding.LayoutDialogBinding
import com.kstech.ks_gaz01.realTime.FloatMultiAdapter
import com.kstech.ks_gaz01.socket.SocketFragmentListener
import com.kstech.ks_gaz01.socket.SocketManagerNew
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


/**
 * author: blankii
 * created on: 2024/4/29 15:55
 * description: 首界面 配置参数界面
 */
class ConfigFragment : BaseBindingFragment<FragmentConfigBinding>(FragmentConfigBinding::inflate),
    SocketFragmentListener {
    private lateinit var realTimeFloatTitleParent: DebugDataBean.Parent
    private var lastTitlePosition = 0//title 列表点击序号
    private var lastItemPosition = 0//item 列表点击序号
    private lateinit var debugDataTitleAdapter: DebugDataTitleAdapter//titleAdapter
    private lateinit var debugDataItemAdapter: DebugDataItemAdapter//itemAdapter
    private lateinit var lastWriteValue: String//上一个写入的对话框参数
    private lateinit var currentGroupAddress: String
    val itemList = ArrayList<DebugDataBean.Item>()//itemAdapter数据源
    private lateinit var mViewModel: HomeViewModel

    /**
     * floatAdapter
     */
    private lateinit var floatAdapter: FloatMultiAdapter
    private lateinit var floatArray: ArrayList<DebugDataBean.Item>


    override fun onCreateInit() {
        /**
         * 连接socket
         * todo 自动切换测试ip
         */
//        val ip = "192.168.54.167"
        val ip = "10.10.100.254"
        SocketManagerNew.initEasySocket(requireActivity(), ip, SOCKET_PORT)
        SocketManagerNew.subscribeSocketFragmentListener(this)
        mViewModel = ViewModelProvider(requireActivity())[HomeViewModel::class.java]
    }

//    init {
//        "init is working".logi(TAG)
//    }

    override fun onInitView() {
        initAdapter()
        initBinding()
//        initNav()
        /**
         * 设置左侧默认选中
         */
        DebugDataBean.getParentByIndex(lastTitlePosition).selected = true
        debugDataTitleAdapter.notifyDataSetChanged()
        /**
         * 初始化右侧
         */
        updateItemPartView()
        /**
         * 初始化realTimeFloat
         */
        setFloatFirst()
        /**
         * 监听ViewModel
         */
        mViewModel.currentPage.observe(this, Observer {
            if (it == FragmentPage.HOME_CONFIG) {
                SocketManagerNew.subscribeSocketFragmentListener(this@ConfigFragment)
                //开启通讯,加入队列
                sendDataToSocket()
            }
        })
        val keyIsExistRt = DebugDataBean.xmlSettings[XML_XS_RTB]
        if (!(keyIsExistRt != null && keyIsExistRt && floatDataType == "left")) {
            binding.floatPart.visibility = View.GONE
        } else {

            /**
             * 初始化floatRecyclerView
             */
            floatArray = ArrayList()
            binding.floatPart.layoutManager = QuickGridLayoutManager(requireActivity(), 8)
            floatAdapter = FloatMultiAdapter(floatArray)
            binding.floatPart.setOnTouchListener(View.OnTouchListener { v, event -> true })
//            floatPart.isNestedScrollingEnabled = false
            binding.floatPart.addItemDecoration(GridSpaceItemDecoration(10, 10))
            binding.floatPart.adapter = floatAdapter
            floatArray.addAll(DebugDataBean.xmlMap[XML_REALTIME_FLOAT]!![0].itemList)
            floatAdapter.notifyDataSetChanged()
        }
    }

    private fun initNav() {
        /**
         * 监听navController
         */
//        findNavController().addOnDestinationChangedListener { controller, destination, arguments ->
//            if (destination.id == R.id.homeFragment) {
//                when (mViewModel.currentPage) {
//                    HomeFragment.ViewPagerPage.CONFIG_PAGE -> {
//                        "执行1${mViewModel.currentPage}".loge(TAG)
//
//                    }
//
//                    HomeFragment.ViewPagerPage.REALTIME_PAGE -> {
//                        "执行2${mViewModel.currentPage}".loge(TAG)
//                    }
//                }
//            } else {
//                "执行3${mViewModel.currentPage}".loge(TAG)
//                SocketManagerNew.unSubscribeSocketFragmentListener()
////                globalPrintln("unSubscribeSocketFragmentListener")
//            }
//        }
    }

    private fun initAdapter() {
        /**
         * 初始化 debugDataTitleAdapter
         */
        debugDataTitleAdapter = DebugDataTitleAdapter().apply {
            this.submitList(DebugDataBean.xmlMap[XML_CONFIG])
            this.setOnItemClickListener { adapter, view, position ->
                //todo 感觉点击切换的ui反应有些慢
                if (lastTitlePosition == position) {
                    return@setOnItemClickListener
                }
                DebugDataBean.getParentByIndex(lastTitlePosition).selected = false
                DebugDataBean.getParentByIndex(position).selected = true
                this.notifyItemChanged(lastTitlePosition)//更新旧index
                this.notifyItemChanged(position)//更新新index
                this.notifyDataSetChanged()

                lastTitlePosition = position
                updateItemPartView()//点击之后更新右半区UI
            }
        }
        /**
         * 初始化 debugDataItemAdapter
         */
        debugDataItemAdapter = DebugDataItemAdapter()
        debugDataItemAdapter.submitList(itemList)
        debugDataItemAdapter.setOnItemClickListener { adapter, view, position ->
            lastItemPosition = position
            //显示对话框
            showAlertDialog(position)
        }
    }

    private fun initBinding() {
        binding.apply {
            /**
             * floatingActionButton
             */
//            this.floatingActionButton.setOnClickListener {
//                saveThisPage()
//            }
            /**
             * 加载 titleAdapter
             */
            this.titleRecyclerView.apply {
                this.layoutManager = LinearLayoutManager(requireActivity())
                this.addItemDecoration(
                    DividerItemDecoration(
                        requireContext(), R.color.white
                    )
                )
                this.adapter = debugDataTitleAdapter
            }
            /**
             * 加载 itemAdapter
             */
            this.itemRecyclerView.apply {
                /**
                 * 屏幕适配 当xxhdpi及xxxhdpi
                 */
                if (HardwareInfoUtil.getDpiString(requireActivity()).contains("xxhdpi")) {
                    this.layoutManager = object : QuickGridLayoutManager(requireActivity(), 3) {
                        override fun canScrollVertically(): Boolean {
                            return false
                        }
                    }
                } else {
                    this.layoutManager = object : QuickGridLayoutManager(requireActivity(), 4) {
                        override fun canScrollVertically(): Boolean {
                            return false
                        }
                    }
                }
                this.addItemDecoration(GridSpaceItemDecoration(10, 10))
                this.adapter = debugDataItemAdapter
                this.setHasFixedSize(true)
                this.isNestedScrollingEnabled = false
            }
            /**
             * 加载 tabs点击事件
             */
            this.childTabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    if (DebugDataBean.getChildListByIndex(lastTitlePosition)[tab!!.position].isExistedGroupTab) {//如果存在groupTabs
                        binding.groupTabs.visibility = View.VISIBLE
                        val groupList =
                            DebugDataBean.getGroupListByIndex(lastTitlePosition, tab!!.position)
                        binding.groupTabs.removeAllTabs()
                        for (i in groupList.indices) {
                            binding.groupTabs.addTab(
                                binding.groupTabs.newTab().setText(groupList[i].name), false
                            )
                        }
                        binding.groupTabs.getTabAt(0)!!.select()
                    } else {//如果不存在groupTabs
                        binding.groupTabs.visibility = View.GONE
                        itemList.clear()
                        val list = DebugDataBean.getItemListByIndex(
                            lastTitlePosition,
                            tab!!.position,
                        )
                        list.forEach {
                            it.writeRes = false
                        }
                        itemList.addAll(
                            list
                        )
//                        spaceView()
                        debugDataItemAdapter.notifyDataSetChanged()
                        //开启通讯,加入队列
                        sendDataToSocket()
                    }
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {

                }

                override fun onTabReselected(tab: TabLayout.Tab?) {

                }
            })
            /**
             * groupTabs
             */
            this.groupTabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    if (binding.groupTabs.visibility == View.GONE) {
                        return
                    }
                    itemList.clear()
                    val list = DebugDataBean.getItemListByIndex(
                        lastTitlePosition, binding.childTabs.selectedTabPosition, tab!!.position
                    )
                    list.forEach {
                        it.writeRes = false
                    }
                    itemList.addAll(
                        list
                    )
                    sendDataToSocket()
//                    spaceView()
                    debugDataItemAdapter.notifyDataSetChanged()
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {

                }

                override fun onTabReselected(tab: TabLayout.Tab?) {

                }
            })
        }
    }

    /**
     * 添加一块空白控件
     */
    private fun spaceView() {
        /**
         * 页面适配，如果数据占满页面的时候，保存按钮会挡住一个数据
         */
        if (itemList.size >= 12 && itemList.size % 4 == 0) {
            binding.spaceView.visibility = View.VISIBLE
        } else {
            binding.spaceView.visibility = View.GONE
        }
    }

//    private fun sendDataToSocket() {
//        if (itemList.size == 0) {
//            return
//        }
//        currentGroupAddress = (itemList[0].para0.toInt() - 1).toString()
//        SocketManagerNew.addReadyLooperList(
//            false, arrayListOf(
//                SocketManagerNew.ReadBean(
//                    currentGroupAddress, itemList[0].para2, itemList.size
//                )
//            )
//        )
//    }

    private fun sendDataToSocket() {
        if (itemList.size == 0) {
            return
        }
        currentGroupAddress = (itemList[0].para0.toInt() - 1).toString()
        if (::realTimeFloatTitleParent.isInitialized) {
            SocketManagerNew.addReadyLooperList(
                true, arrayListOf(
                    SocketManagerNew.ReadBean(
                        currentGroupAddress, itemList[0].para2, itemList.size
                    ), SocketManagerNew.ReadBean(
                        (realTimeFloatTitleParent.itemList[0].para0.toInt() - 1).toString(),
                        realTimeFloatTitleParent.itemList[0].para2,
                        realTimeFloatTitleParent.itemList.size
                    )
                )
            )
        } else {
            SocketManagerNew.addReadyLooperList(
            false, arrayListOf(
                SocketManagerNew.ReadBean(
                    currentGroupAddress, itemList[0].para2, itemList.size
                )
            )
        )
        }
    }

    /**
     * viewpager 滑动时响应
     */
    override fun onResume() {
        super.onResume()
        SocketManagerNew.subscribeSocketFragmentListener(this)

        //开启通讯,加入队列
        sendDataToSocket()
    }

    /**
     * viewpager 滑动时响应
     */
    override fun onPause() {
        super.onPause()
        SocketManagerNew.unSubscribeSocketFragmentListener()
    }


    /**
     * 更新右半区
     */
    private fun updateItemPartView() {
        /**
         * 控制 tabs显示隐藏 装载数据
         */
        val parent = DebugDataBean.getParentByIndex(lastTitlePosition)
        if (!parent.isExistedChildTab) {
            binding.childTabs.visibility = View.GONE
            binding.groupTabs.visibility = View.GONE
        } else {
            binding.childTabs.apply {
                visibility = View.VISIBLE
                this.removeAllTabs()
                parent.childList.forEach {
                    this.addTab(newTab().setText(it.name), false)
                }
                binding.childTabs.getTabAt(0)!!.select()
            }
        }
    }

    /**
     * 显示输入对话框
     */
    private fun showAlertDialog(position: Int) {
        val dialogBinding = LayoutDialogBinding.inflate(layoutInflater)
//        dialogBinding.editTextNumber.keyListener = DigitsKeyListener.getInstance("0123456789-")
        val currentProject = itemList!![position]
        val dialogBuilder = AlertDialog.Builder(requireActivity()).setView(dialogBinding.root)
            .setTitle("${currentProject.para1}").setMessage("请修改该参数").setPositiveButton(
                "OK"
            ) { dialog, which ->
                lastWriteValue = dialogBinding.editTextNumber.text.toString()
                if (lastWriteValue.isEmpty()) {
                    "请填写数值".showSnackBar()
                    return@setPositiveButton
                }
                //点击OK按钮，加入写入消息队列
                SocketManagerNew.sendWriteMsg(
                    currentProject.para0,
                    dialogBinding.editTextNumber.text.toString(),
                    currentProject.isNegativeNumber
                )
            }.setNegativeButton(
                "Cancel"
            ) { dialog, which ->

            }
        dialogBinding.editTextNumber.requestFocus()
        dialogBuilder.show()
    }


    override fun writeSuccess(address: String, value: String) {
        if (XML_ADDRESS_SAVE_PARAM.contains(address)) {
            /**
             * 读取一下 读取是否标定成功
             */
            "保存成功".showSnackBar()
//            SocketManagerNew.addReadyLooperList(
//                false, arrayListOf(
//                    SocketManagerNew.ReadBean(
//                        XML_ADDRESS_SAVE_PARAM_SUCESS
//                    )
//                )
//            )
        } else {
            /**
             * 写入成功一个参数
             * 立马发送一个数读
             */
            if (lastItemPosition >= itemList.size) {
                return
            }
            val currentItem = itemList[lastItemPosition]
            if (currentItem.para0.substring(1) == address) {
                currentItem.writeRes = true
                SocketManagerNew.addReadyLooperList(
                    false, arrayListOf(
                        SocketManagerNew.ReadBean(
                            currentItem.para0
                        )
                    )
                )
            }
        }
    }

    fun setFloatFirst() {
        /**
         * 如果XML_REALTIME_FLOAT 配置了参数
         * 则返回他的第一条数据
         */
        val keyIsExistRt = DebugDataBean.xmlSettings[XML_XS_RTB]
        if (keyIsExistRt != null && keyIsExistRt && floatDataType == "left" && xmlMap[XML_REALTIME_FLOAT]!!.size != 0) {
            realTimeFloatTitleParent = xmlMap[XML_REALTIME_FLOAT]!![0]
        }
    }
    override fun readSuccess(address: String, result: ArrayList<String>) {
        CoroutineScope(Dispatchers.Main).launch {
            //更新一组数据
            if (currentGroupAddress == address) {
                for (i in result.indices) {
                    itemList[i].revData =
                        CalcUtil.Hex2IntStr(result[i], itemList[i].isNegativeNumber)
                }
                debugDataItemAdapter.notifyDataSetChanged()
            } else if (::realTimeFloatTitleParent.isInitialized && (realTimeFloatTitleParent.itemList[0].para0.toInt() - 1).toString() == address) {
                for (i in floatArray.indices) {
                    floatArray[i].revData =
                        CalcUtil.Hex2IntStr(result[i], floatArray[i].isNegativeNumber)
                }
                floatAdapter.notifyDataSetChanged()
            }
            //写入单个数据之后更新该单个数据
            else if (lastItemPosition < itemList.size && itemList[lastItemPosition].para0 == address) {
                itemList[lastItemPosition].revData =
                    CalcUtil.Hex2IntStr(result[0], itemList[lastItemPosition].isNegativeNumber)
                debugDataItemAdapter.notifyDataSetChanged()
            }
        }

//        else if (XML_ADDRESS_SAVE_PARAM_SUCESS==address) {
//            if (result[0] == "A5A5") {
//                "保存成功".showMsgInfo()
//            } else {
//                "保存失败".showMsgInfo()
//            }
//        }
    }
}